import User from "../../utils/user";
import msg from "../../utils/msg";
import { GetSignDetail,SignIn } from "../../utils/request/api";
import { Location, signDetail, SignParamActivity, SignParamCourse} from "./interface";
import { Course } from "../curriculum/interface";
const app = getApp<IAppOption>();

// pages/signIn/signIn.ts
var amapFile = require('../../libs/amap-wx.130');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //课程与活动签到共用
    signDetail:{} as signDetail,
		myLocation:{} as any,
    markers:'' as any,
    is_signed:false as Boolean,
    other_id:0 as number | string,
    other_type:'' as '课程' | '活动',
    //课程需要的额外参数
    startDate: app.globalData.startDate as string,//学期开始日期
    nowWeeks:app.globalData.nowWeeks as number,//第几周
    course_msg:{} as Course,
    //签到签退开始时间结束时间
    sign_start:'' as string,
    sign_end:'' as string,
    signout_start:'' as string,
    signout_end:'' as string,
  },
  /**
   * @funciton 签到
   */
	signIn:async function(){
    let signDetail=this.data.signDetail;
    let myLocation=this.data.myLocation;
    let course_msg=this.data.course_msg;
    //检查是否在签到半径 暂时不检查
    //if(!this.cheakLocation(myLocation,signDetail))return;
    let user=new User;
    //检查是否在签到时间 是否迟到
    //课程
    if(this.data.other_type=='课程'){
      let data = this.checkCourseSignInValid();
      if(data.statu!=false){
        let type:any=data.statu;
        console.log('signIn!');
        SignIn({sign_id:signDetail.sign_id ,other_id:course_msg.id, name:user.name ,code:user.code ,week:this.data.nowWeeks,type:type,s_type:'课程'})
        .then((res:any)=>{
          //
          if(res.data.code=="500"){
            msg.show("已经签到过啦",'');return;
          }
          if(data.title!='')
          msg.show(data.title,data.content);
        })
      }
    }
    //
  },
  cheakLocation:async function(location:Location,signDetail:signDetail){
    //检查是否在签到半径
    let distance=this.GetDistance(location.latitude,signDetail.location.latitude,location.longitude,signDetail.location.longitude);
    //console.log('distance='+distance);
    if(distance>signDetail.radius){
     msg.show('与签到点距离过远','签到失败');
      return false;
    }
    return true;
  },
  cheakTime(){
    
  },
  init:async function(){
    //初始化签到点
    let signDetail=this.data.signDetail;
    this.pushMarker(signDetail.location.latitude,signDetail.location.longitude,'签到点');
    //初始化定位点
    wx.showLoading({
      title: '定位中，请稍等',
    });
    let location:any =await this.getMyLocation().then((res:any)=>{return res;});
    this.setData({myLocation:location});
    wx.hideLoading();
    this.pushMarker(location.latitude,location.longitude,'定位所在地点');
  },
  onClickLeft(){
    wx.navigateBack();
  },
  /**
   * 生命周期函数--监听页面加载 需传入课程或活动的id
   */
  onLoad:async function(option:any) {
    let nowWeeks=app.globalData.nowWeeks;
    let startDate=app.globalData.startDate;
    this.setData({
      nowWeeks:nowWeeks,
      startDate:startDate,
    });
    //
    if(option.sign_type=='课程'){//课程的情况
      let s_option:SignParamCourse = option;
      this.setData({
        other_id:s_option.course_id,
        other_type:s_option.sign_type,
        course_msg:JSON.parse(option.course_msg),
      })
    }
    else{
      let s_option:SignParamActivity = option;
      this.setData({
        other_id:s_option.activity_id,
        other_type:s_option.sign_type,
      })
    }
  },
  pushMarker(la:number,lo:number,title:string){
    let markers=this.data.markers;
    let id=this.data.markers.length;
    markers.push({
      id: id,
      width:'30px',
      height:'40px',
      latitude: la,
      longitude: lo,
      label:{
        content: title,  //文本
        color: '#FF0202',  //文本颜色
        borderRadius: 3,  //边框圆角
        borderWidth: 1,  //边框宽度
        borderColor: '#FF0202',  //边框颜色
        bgColor: '#ffffff',  //背景色
        padding: 5,  //文本边缘留白
        textAlign: 'center'  //文本对齐方式。有效值: left, right, center
      },
    });
    this.setData({
      markers:markers,
    })
  },
  getMyLocation(){
    return new Promise((resolve,reject)=>{
    let myAmapFun = new amapFile.AMapWX({key:'1ad54dc313a0320dcddaecf63322f9f4'});
    myAmapFun.getRegeo({
      success: function(data:any){
        //成功回调
        resolve(data[0]);
      },
      fail: function(info:any){
        //失败回调
        reject(info);
      }
    });
    })
  },

  //进行经纬度转换为距离的计算
   Rad(d:number){
    return d * Math.PI / 180.0;//经纬度转换成三角函数中度分表形式。
    },
    //计算距离，参数分别为第一点的纬度，经度；第二点的纬度，经度
  GetDistance(lat1:number,lat2:number,lng1:number,lng2:number){
    var radLat1 = this.Rad(lat1);
    var radLat2 = this.Rad(lat2);
    var a = radLat1 - radLat2;
    var  b = this.Rad(lng1) - this.Rad(lng2);
    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) +
    Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
    s = s *6378.137 ;// EARTH_RADIUS;
    s = Math.round(s * 10000) / 10; //输出为米
    return s;
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },
  //获取课程下一次签到日期
  getNextCourseDate(signDetail:signDetail){

  },
  //获取签到签退的开始结束时间
  _getSignTime(signDetail:signDetail){
       
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow:async function() {
    //this.getMyLocation().then((res:any)=>{console.log(res)});
    //获取签到详情
    msg.Loading('获取签到详情中');
    if(this.data.other_id==0){
      msg.hideLoading();
      msg.show('程序错误','非法的参数');
      return;
    }
    await GetSignDetail({other_id:this.data.other_id,other_type:this.data.other_type})
    .then((res:any)=>{
      if(this.data.other_type=='课程')
      this.setData({
        signDetail:this.getCourseTime(res.data.data),
      });
      else
      this.setData({
        signDetail:res.data.data,
      });
    })
    .catch((res:any)=>{
      console.log(res);
      msg.show('获取签到详情失败','正在返回');
      setTimeout(function(){
        wx.navigateBack();
      },1000);
    });
    msg.hideLoading();
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  //返回加减去分钟数之后的日期 暂时没用
  _subtractMinutesFromDate(date: string, minutes: string , type:'add' | 'minus'): string {
    // 将浮点数转换为整数
    let minute = Math.floor(parseInt(minutes));
    
    // 将日期字符串转换为 Date 对象
    const currentDate = new Date(date);
  
    // 计算减去分钟数之后的日期
    if(type=='add')
      currentDate.setMinutes(currentDate.getMinutes() + minute);
    else 
    currentDate.setMinutes(currentDate.getMinutes() - minute);
    // 返回新日期的字符串格式
    return currentDate.toISOString();
  },
  /**
  * @function 获取今天是周几
  */
 _getDay(): string {
  const today = new Date().getDay();
  let chineseNumber='';
  switch (today) {
    case 1:
      chineseNumber = '一';
      break;
    case 2:
      chineseNumber = '二';
      break;
    case 3:
      chineseNumber = '三';
      break;
    case 4:
      chineseNumber = '四';
      break;
    case 5:
      chineseNumber = '五';
      break;
    case 6:
      chineseNumber = '六';
      break;
    case 0:
      chineseNumber = '七';
      break;
  }
  // 因为返回值范围是 0-6，需要将星期天（0）转换为 7
  return chineseNumber;
  },
  //获取课程的开始时间与结束时间
  getCourseTime(signDetail:signDetail):signDetail{
    let course_msg:Course = this.data.course_msg;
    let time = course_msg.time.split('-');
    signDetail.start_time =course_msg.weeks+'周 周'+course_msg.day+' '+this._getCourseStartTime(time[0])+'-'+this._getCourseEndTime(time[1]);
    return signDetail;
  },
  /**
  * @function 获取上课时间
  */
 _getCourseStartTime(index:string){
  let time = '';
  switch(index){
    case '1':
      time = '8:30';
      break;
    case '2':
      time = '9:20';
      break;
    case '3':
      time = '10:20';
      break;
    case '4':
      time = '11:10';
      break;
    case '5':
      time = '14:30';
      break;
    case '6':
      time = '15:20';
      break;
    case '7':
      time = '16:10';
      break;
      case '8':
        time = '16:50';
      break;
      case '9':
        time = '19:00';
      break;
      case '10':
        time = '19:50';
      break;
      case '11':
        time = '20:40';
      break;
  };
  return time;
 },
 /**
  * @function 获取下课时间
  */
 _getCourseEndTime(index:string){
  let time = '';
  switch(index){
    case '2':
      time = '10:00';
      break;
    case '3':
      time = '11:00';
      break;
    case '4':
      time = '11:50';
      break;
    case '5':
      time = '15:10';
      break;
    case '6':
      time = '16:00';
      break;
    case '7':
      time = '16:50';
      break;
      case '8':
        time = '17:40';
      break;
      case '9':
        time = '19:40';
      break;
      case '10':
        time = '20:30';
      break;
      case '11':
        time = '21:20';
      break;
  };
  return time;
 },
 /**
  * @function 检查课程是否可以签到
  * @return false | '正常签到' | '迟到'
  */
 checkCourseSignInValid():{statu:false | '正常签到' | '迟到',title:string,content:string}{
   let nowWeeks:number = this.data.nowWeeks;
   let today:string = this._getDay();
   let course_msg=this.data.course_msg;
   let signDetail=this.data.signDetail;
   if(this._checkRange(course_msg.weeks,nowWeeks.toString())&&today==course_msg.day){ 
     //今天上课
     //检查是否在签到时间内
      let timerange=this._getCourseStartTime(course_msg.time[0])+'-'+this._getCourseEndTime(course_msg.time[2]);
      return this._checkSignStatus(timerange,signDetail.sign_start,signDetail.sign_end);
    }
    else msg.show('这节课今天不上哦','请在当天签到');
    return{statu:false,title:'',content:''};
 },
 _checkRange(range: string, number: string): boolean {
  const [start, end] = range.split("-").map(Number);
  const num = Number(number);
  if (Number.isNaN(start) || Number.isNaN(end) || Number.isNaN(num)) {
    throw new Error("Invalid input");
  }
  return num >= start && num <= end;
  },
  /**
  * @function 检查是否在课程正常签到时间内
  */
 _checkSignStatus(timeRange: string, minutesBefore: number, minutesAfter: number):{statu:false | '正常签到' | '迟到',title:string,content:string} {
  const currentTime = new Date();
  
  // Split the time range into start time and end time
  const [startTime, endTime] = timeRange.split('-').map(time => {
    const [hours, minutes] = time.split(':').map(Number);
    return new Date(currentTime.getFullYear(), currentTime.getMonth(), currentTime.getDate(), hours, minutes);
  });
  
  // Calculate the time ranges for early sign-in and late arrival
  //签到开始时间
  const earlySignInStart = new Date(startTime.getTime() - minutesBefore * 60000);
  //迟到开始时间
  const earlySignInEnd = new Date(startTime.getTime() + minutesAfter * 60000);
  // const lateArrivalStart = endTime;
  // const lateArrivalEnd = new Date(endTime.getTime() + minutesAfter * 60000);
  if (currentTime >= earlySignInStart && currentTime <= earlySignInEnd) {
    //return "正常签到";
    //msg.show("签到成功！",'');
    return {statu:"正常签到",title:"签到成功！",content:''};
  } else if (currentTime >= earlySignInEnd && currentTime <= endTime) {
    //return "迟到";
    //msg.show("签到成功！",'但是迟到了...');
    return {statu:"迟到",title:"签到成功！",content:'但是迟到了...'};
  } else if (currentTime > endTime) {
    //return '签到时间已过';
    //msg.show("签到时间已过",'最晚签到时间: '+endTime.getHours()+':'+endTime.getMinutes());
    return {statu:false,title:"签到时间已过",content:'最晚签到时间: '+endTime.getHours()+':'+endTime.getMinutes()};
  }else if (currentTime < earlySignInStart) {
    //return '还没到签到时间';
    msg.show("还没到签到时间",'最早签到时间: '+earlySignInStart.getHours()+':'+earlySignInStart.getMinutes());
    return {statu:false,title:"还没到签到时间",content:'最早签到时间: '+earlySignInStart.getHours()+':'+earlySignInStart.getMinutes()};
  }
  return{statu:false,title:'',content:''};
  },
})